const {app, BrowserWindow, ipcMain, session, desktopCapturer, screen } = require('electron')
const { saveTempBlob, saveFile,  } = require('./ffmpegmodel/index')

// const WinState = require('electron-win-state').default
const path = require('path')
const fs = require('fs')
const {
    createIpcCam,
    createIpcTit,
    createIpcHotk,
    createIpcPre,
    createIpcSet
} = require('./createviewmodel/index')

// 桌面宽高
// let screenW
// let screenH


let mainWin;
const createMainWin = () => {
    // const winState = new WinState({
    //     defaultWidth: 960,
    //     defaultHeight: 515,
    //     dev: true
    // })
    // 准备pc窗口
    mainWin = new BrowserWindow({
        // ...winState.winOptions,
        width:960,
        height:515,
        icon: path.join(__dirname, './src/assets/image/favicon-32x32.png'),
        webPreferences: {
            // 允许js文件使用require模块引入方式
            // nodeIntegrationInWorker: true,
            nodeIntegration: true,
            // 将脚本附在渲染进程上，preload属性传入脚本路径 预加载
            preload: path.resolve(__dirname, './preload.js')
        },
        titleBarStyle: 'hidden',
        show: false,
        frame: false
    })
    mainWin.setAspectRatio(1536/824)
    // 载入html
    mainWin.loadFile('./src/index.html')
    // 载入网页
    // mainWin.loadURL('http://localhost:3000');
    // winState.manage(mainWin)
    // 页面加载完成后打开窗口
    mainWin.on('ready-to-show', ()=> {
        mainWin.show()
    })
    mainWin.webContents.openDevTools()
}

// 自定义menu
function customMenu() {
    const menu = Menu.buildFromTemplate([
        {
            label: app.name,
            submenu: [
                {
                    click: () => mainWin.webContents.send('update-counter', 1),
                    label: 'Increment',
                },
                {
                    click: () => mainWin.webContents.send('update-counter', -1),
                    label: 'Decrement',
                }
            ]
        }
    ])
    Menu.setApplicationMenu(menu)
}


// PCapp会在ready完成后执行whenReady函数
app.whenReady().then(()=> {
    createMainWin();
    // 监听预览窗口打开事件
    createIpcPre(mainWin)
    // 监听摄像头窗口打开事件
    createIpcCam();
    // 监听标题窗口打开事件
    createIpcTit()
    // 监听热键窗口打开事件
    createIpcHotk()
    createIpcSet(mainWin)

    // 屏幕共享
    session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
        desktopCapturer.getSources({ types: ['screen'] }).then((sources) => {
            callback({ video: sources[0], audio: 'loopback' })
        })
    }, { useSystemPicker: true });

    // 检擦tempPath文件夹中是否有hhlptemporary文件夹,如果没有则在tempPath文件夹中创建hhlptemporary文件夹
    if (!fs.existsSync(path.resolve(app.getPath('temp'), 'hhlptemporary'))) {
        fs.mkdirSync(path.resolve(app.getPath('temp'), 'hhlptemporary'))
    }
    // // 桌面宽高
    // const primaryDisplay = screen.getPrimaryDisplay()
    // const { width, height }= primaryDisplay.workAreaSize
    // console.log(width, height)
    
    // (macOS)没有窗口则打开一个窗口
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

// 关闭所有窗口时退出应用(macOS)
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit();
})

// 控制窗口
ipcMain.on('controlMainwin', (event, data) => {
    if (data === 'min') {
        mainWin.minimize()
    } else if (data === 'max') {
        mainWin.maximize()
    } else if (data === 'close') {
        mainWin.close()
    }
})

// 弹窗警告
ipcMain.on('show-alert', (event, data) => {
    dialog.showMessageBox({
        type: 'info',
        title: '提示',
        message: data
    })
})

ipcMain.on('save-temp-blob',(event, data, mark)=> {
    saveTempBlob(data, mark)
})
ipcMain.handle('save-file',()=> {
    return saveFile(app.getPath('temp'), app.getPath('downloads'))
})
